<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { get, post } from '@/utils/service'
import { showNotify } from 'vant' // 可选：根据你的UI库引入提示组件，如 Element-UI, Vant 等
import { SERVICE_MOBILEPHONE, VUE_APP_BASE_API } from '@/utils/baseConfig'
import router from '@/router'
function onClickLeft() {
  window.history.back()
}
const userouter = useRoute()
const userouters = useRouter()
const customerId = (userouter.query.customerId as string) || 0
const custName = ref('')
const mobilePhone = ref('')
const loadingStatus = ref(false)
const sexChecked = ref('男')
const entepriseColumns = ref([])
const brandColumns = ref([])
const reccomendCustomer = ref({})
//门店选择器
const resultEnterpriseName = ref('')
const enterpriseValue = ref([])
const showEnterprisePicker = ref(false)

onMounted(async () => {
  try {
    queryEnterprise()
    queryBrands()
    if (customerId != '0') {
      getByCustomerId(customerId)
    }
  } catch (error) {
    console.log('onMounted error:' + error)
  }
})
function onEnterpriseConfirm(selectedValues: {}) {
  resultEnterpriseName.value = selectedValues.selectedOptions[0].text
  enterpriseValue.value.push(selectedValues.selectedOptions[0].value)
  showEnterprisePicker.value = false
}

//品牌选择器
const brandName = ref('')
const brandValue = ref([])
const showBrandPicker = ref(false)

function onBrandConfirm(selectedValues: {}) {
  brandName.value = selectedValues.selectedOptions[0].text
  brandValue.value.push(selectedValues.selectedOptions[0].value)
  showBrandPicker.value = false
  carSeriyName.value = ''
  carSeriyColumns.value = []
  queryCarSeriys(selectedValues.selectedOptions[0].value)
}
//品牌选择器
const carSeriyName = ref('')
const carSeriyValue = ref([])
const showCarSeriyPicker = ref(false)
const carSeriyColumns = ref([])

function onCarSeriyConfirm(selectedValues: {}) {
  carSeriyName.value = selectedValues.selectedOptions[0].text
  carSeriyValue.value.push(selectedValues.selectedOptions[0].value)
  showCarSeriyPicker.value = false
}
// 校验函数返回 true 表示校验通过，false 表示不通过

function onFailed(errorInfo: Error | string) {
  console.log('failed', errorInfo)
}
function submitFrm(values: object) {
  console.log('submit', values)
  loadingStatus.value = true // 显示加载状态
  try {
    values.acceptEnterpriseId = enterpriseValue.value[0] || ''
    values.brandId = brandValue.value[0] || ''
    values.carSeriyId = carSeriyValue.value[0] || ''
    values.dbid = customerId || ''
    values.name = custName.value || ''
    post('/recommendCustomerWechatNew/saveWechat', values).then((res) => {
      if (res.code === 0) {
        let previousUrl = userouters.options.history.state?.back || window.location.href
        console.log('上一个链接是:', previousUrl)
        let mesg = ''
        if (previousUrl == null || previousUrl.length <= 0) {
          previousUrl = '/'
          mesg = '即将跳转首页...'
        }
        showNotify({ type: 'success', message: res.msg + mesg, duration: 3000 })
        setTimeout(() => {
          userouters.push(previousUrl)
        }, 1000)
      } else {
        showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
      }
    })
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function queryEnterprise() {
  get('/enterpriseWechatNew/queryWechatSelect', {}).then((res) => {
    entepriseColumns.value = []
    if (res.code === 0) {
      const data = res.data
      entepriseColumns.value.push(data)
    }
  })
}
function getByCustomerId(customerId) {
  get('/recommendCustomerWechatNew/queryByCustomerId', { reccomendCustomerId: customerId }).then(
    (res) => {
      if (res.code === 0) {
        const data = res.data
        reccomendCustomer.value = data
        custName.value = data.name
        mobilePhone.value = data.mobilePhone
        sexChecked.value = data.sex
        enterpriseValue.value[0] = data.acceptEnterpriseId || ''
        brandValue.value[0] = data.brandId || ''
        carSeriyValue.value[0] = data.carSeriyId || ''
        resultEnterpriseName.value = data.acceptEnterpriseName
        carSeriyName.value = data.carSeriyName
        brandName.value = data.brandName
        queryCarSeriys(data.brandId)
      }
    },
  )
}
function queryBrands() {
  get('/brandWechatNew/queryWechatSelect', {}).then((res) => {
    if (res.code === 0) {
      const data = res.data
      brandColumns.value.push(data)
    } else {
      brandColumns.value.push([])
    }
  })
}
function queryCarSeriys(brandId) {
  get('/carSeriyWechatNew/queryWechatList', { brandId: brandId }).then((res) => {
    if (res.code === 0) {
      const data = res.data
      carSeriyColumns.value.push(data)
    } else {
      carSeriyColumns.value.push([])
    }
  })
}
function phoneValidator() {
  return /^1\d{10}$/.test(mobilePhone.value)
}
function nameValidator() {
  return /^[\u4e00-\u9fa5]{2,10}$/.test(custName.value)
}
function viewHistoryOnline() {
  router.push('/myRecommendCustomer')
}
</script>
<template>
  <van-nav-bar title="推荐客户" left-text="返回" left-arrow @click-left="onClickLeft" />
  <div class="mainContent">
    <div style="margin: auto 0; text-align: center; padding: 40px 20px; width: 100%">
      <van-image
        width="5rem"
        height="5rem"
        :src="VUE_APP_BASE_API + '/images/vue/recommendCustomer.png'"
        position="center"
      />
    </div>
    <van-form @failed="onFailed" @submit="submitFrm">
      <input type="hidden" :value="reccomendCustomer.dbid" name="dbid" id="dbid" />
      <van-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          v-model="custName"
          required="true"
          label="姓名"
          name="custName"
          placeholder="客户姓名"
          :value="reccomendCustomer.name"
          :rules="[
            { required: true, message: '请填写姓名' },
            { validator: nameValidator, message: '请输入购车客户姓名,2-10个中文字符' },
          ]"
        />
        <van-field
          v-model="mobilePhone"
          label="联系电话"
          required="true"
          name="mobilePhone"
          placeholder="客户联系电话"
          type="tel"
          :rules="[
            { required: true, message: '请填写手机号码' },
            { validator: phoneValidator, message: '请输入正确的手机号格式', trigger: 'onBlur' },
          ]"
        />
        <van-field name="sex" label="称呼">
          <template #input>
            <van-radio-group v-model="sexChecked" direction="horizontal">
              <van-radio name="男" model-value="男" checked-color="#c82030">先生</van-radio>
              <van-radio name="女" model-value="女" checked-color="#c82030">女士</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="resultEnterpriseName"
          is-link
          readonly
          name="acceptEnterpriseName"
          label="门店"
          placeholder="点击选择门店"
          @click="showEnterprisePicker = true"
        />
        <van-popup :show="showEnterprisePicker" destroy-on-close position="bottom">
          <van-picker
            :columns="entepriseColumns"
            :model-value="enterpriseValue"
            @confirm="onEnterpriseConfirm"
            @cancel="showEnterprisePicker = false"
          />
        </van-popup>
        <van-field
          v-model="brandName"
          is-link
          readonly
          name="brandName"
          label="品牌"
          placeholder="点击选择品牌"
          @click="showBrandPicker = true"
        />
        <van-popup v-model:show="showBrandPicker" destroy-on-close position="bottom">
          <van-picker
            :columns="brandColumns"
            :model-value="brandValue"
            @confirm="onBrandConfirm"
            @cancel="showBrandPicker = false"
          />
        </van-popup>
        <van-field
          v-model="carSeriyName"
          is-link
          readonly
          name="carSeriyName"
          label="车系"
          placeholder="点击选择车系"
          @click="showCarSeriyPicker = true"
        />
        <van-popup v-model:show="showCarSeriyPicker" destroy-on-close position="bottom">
          <van-picker
            :columns="carSeriyColumns"
            :model-value="carSeriyValue"
            @confirm="onCarSeriyConfirm"
            @cancel="showCarSeriyPicker = false"
          />
        </van-popup>
      </van-cell-group>
      <br />
      <br />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          :loading="loadingStatus"
          loading-type="spinner"
          loading-text="提交中..."
          native-type="submit"
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
  <div class="mainContent" style="margin-bottom: 32px">
    <p style="font-size: 14px">
      若您在推荐客户过程中有任何为题请拨打：<a
        :href="'tel:' + SERVICE_MOBILEPHONE"
        style="color: var(--main-color)"
        >{{ SERVICE_MOBILEPHONE }}</a
      >
    </p>
    <p style="font-size: 14px">
      我的推荐客户：<a style="color: var(--main-color)" @click="viewHistoryOnline">点击查看</a>
    </p>
  </div>
</template>

<style></style>
